package com.sk.seckilldemo.service;

import com.sk.seckilldemo.entity.SeckillActivity;
import com.sk.seckilldemo.mapper.SeckillActivityMapper;
import com.sk.seckilldemo.util.Response;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 秒杀活动接口实现
 * */
@Service
@Transactional
@RequiredArgsConstructor
public class SeckillActivityService {
    private final SeckillActivityMapper activityMapper;

    /**
     * 添加一个秒杀活动。
     * */
    public Response insert(SeckillActivity seckillActivity){
        seckillActivity.setStartTime(LocalDateTime.now());
        seckillActivity.setEndTime(LocalDateTime.now().plusHours(2));
        int affected = activityMapper.insert(seckillActivity);
        if(affected == 0){
            return new Response(501,"添加失败",null);
        }else{
            return new Response(200,"添加成功",null);
        }
    }

    /**
     * 扣减库存
     * @return 影响行数
     */
    public Integer reduceStock(Integer activityId){
        return activityMapper.reduceStock(activityId);
    }

    /**
     * 恢复库存
     */
    private Integer increaseStock(Integer activityId){
        return activityMapper.increaseStock(activityId);
    }

    /**
     * 获取当前库存
     */
    public Integer getStock(Integer activityId){
        SeckillActivity activity = activityMapper.selectById(activityId);
        return activity != null ? activity.getStock(): 0;
    }
}
